﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Graphics;

using GameEngine;
using GameBoardViewer.Common;
using System.Windows;

namespace GameBoardViewer.GameBoardViewerControl
{
    public class GameBoardViewerControl : IMainBoard
    {
        protected const int _backgroundSize = 600;

        protected int _fullScreenWidth = 1280;
        protected int _fullScreenHeight = 1024;

        protected int _restoreDataCount = 0;
        protected int _backupWidth;
        protected int _backupHeight;

        protected Game _game;
        protected GraphicsDeviceManager graphics;
        protected IBoardControl _captureControl;
        protected List<IBoardControl> childControls;
        protected bool _b3DViewOn;

        protected bool _inEditMode;

        protected Texture2D m_TextureBackground;

        protected GameBoardButton m_SwitchButton;
        protected GameBoardButton m_FullScreenButton;
        protected GameBoardViewer.Board3D.Board3DControl m_Board3D;
        protected GameBoardViewer.Board2D.Board2DControl m_Board2D;

        protected GameManager m_GameManager;

        public event GameMoveDelegate GameMoveDoneEvent;

        public bool InEditMode
        {
            get
            {
                return _inEditMode;
            }
        }

        public int GameBoardWidth
        {
            get
            {
                return _game == null ? 0 : _game.Window.ClientBounds.Width;
            }
        }

        public int GameBoardHeight
        {
            get
            {
                return _game == null ? 0 : _game.Window.ClientBounds.Height;
            }
        }

 

        public GameBoardViewerControl(Game game)
        {
            _game = game;
            _game.Content.RootDirectory = "Content";
        }


        public void SetData(GameManager _gameManager, string sFullscreenWindowTitle)
        {
            m_GameManager = _gameManager;
            if (m_Board3D != null)
                m_Board3D.SetData(_gameManager);
            if (m_Board2D != null)
                m_Board2D.SetData(_gameManager);

        }

        public void Initialize()
        {
            _captureControl = null;
            _b3DViewOn = true;
            childControls = new List<IBoardControl>();

            m_Board3D = new Board3D.Board3DControl(_game, this);
            m_Board3D.SetData(m_GameManager);
            m_Board3D.GameMoveDoneEvent += new GameMoveDelegate(GameMoveEventDoneHandler);
            m_Board3D.RenderBackgroundEvent += new EventHandler(RenderBackgroundEventHandler);  
            m_Board3D.Initialize();

            m_Board2D = new Board2D.Board2DControl(_game, this);
            m_Board2D.SetData(m_GameManager);
            m_Board2D.GameMoveDoneEvent += new GameMoveDelegate(GameMoveEventDoneHandler);
            m_Board2D.RenderBackgroundEvent += new EventHandler(RenderBackgroundEventHandler);  
            m_Board2D.Initialize();


            m_SwitchButton = new GameBoardButton(_game, this);
            m_SwitchButton.ButtonPressed += new EventHandler(m_SwitchButton_ButtonPressed);
            childControls.Add(m_SwitchButton);

            m_FullScreenButton = new GameBoardButton(_game, this);
            m_FullScreenButton.ButtonPressed += new EventHandler(m_FullScreenButton_ButtonPressed);
            childControls.Add(m_FullScreenButton);

        }

        protected void RenderBackgroundEventHandler(object sender, EventArgs e)
        {
            SpriteBatch spriteBatch = new SpriteBatch(_game.GraphicsDevice);
            Vector2 position = new Vector2(0, 0);
            spriteBatch.Begin();
            spriteBatch.Draw(m_TextureBackground, new Rectangle(0,0, _game.Window.ClientBounds.Width, _game.Window.ClientBounds.Height), new Rectangle(0, 0, (int)m_TextureBackground.Width, (int)m_TextureBackground.Height), Color.White);          
            spriteBatch.End();
        }

        public void LoadContent()
        {
            m_Board3D.LoadContent();           
            m_Board2D.LoadContent();

            m_SwitchButton.LoadContent("2D3DSwitch", 10, 10, enumButtonDockStyle.TopLeft, new Color(0, 0, 255, 128),
                        new Color(255, 255, 0, 128));

            m_FullScreenButton.LoadContent("FullScreen", 70, 10, enumButtonDockStyle.TopLeft, new Color(0, 0, 255, 128),
                        new Color(255, 255, 0, 128));

            m_TextureBackground = new Texture2D(_game.GraphicsDevice, _backgroundSize, _backgroundSize);
            Color[] backgroundData = new Color[_backgroundSize * _backgroundSize];

            float dbl = 0;
            for (int row = 0; row < _backgroundSize; row++)
            {
                Color clr = new Color(dbl, dbl, dbl);

                for (int col = 0; col < _backgroundSize; col++)
                {
                    backgroundData[row * _backgroundSize + col] = clr;
                }

                dbl = (float)1 * (float)row / (float)_backgroundSize;
            }

            m_TextureBackground.SetData<Color>(backgroundData);
        }


        public void UnloadContent()
        {
            _game.Content.Unload();
        }

        public void Update(GameTime gameTime)
        {

            /*if (IsFullScreen == false)
            {
                if (Window.HasFocus == false)
                    return;
            }*/

            // get mouse state
            MouseState mouse = Microsoft.Xna.Framework.Input.Mouse.GetState();
            //if (Window.CheckMouseInWindow(mouse.X, mouse.Y) == false && IsMouseCaptured == false && IsFullScreen == false)
            //{
            //    Window.ResetMouseEventOccured();
            //    return;
            //}

            if (_b3DViewOn == true)
            {
                m_Board3D.Update(mouse);
            }
            else
            {
                m_Board2D.Update(mouse);
            }
        }

        public void Draw(GameTime gameTime)
        {
            _game.GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            _game.GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, new Color(236, 236, 236), 100.0f, 0);


            if (_b3DViewOn == true)
            {
                m_Board3D.Draw();
            }
            else
            {
                m_Board2D.Draw();
            }

            m_SwitchButton.Draw();
            m_FullScreenButton.Draw();
        }

        public void OnLButtonDown(Microsoft.Xna.Framework.Point point)
        {

            if (_captureControl != null)
                _captureControl.OnLButtonDown(point);
            else
            {
                if (_b3DViewOn == true)
                    m_Board3D.OnLButtonDown(point);
                else
                    m_Board2D.OnLButtonDown(point);

                foreach (var item in childControls)
                {
                    item.OnLButtonDown(point);
                }
            }
        }

        public void OnLButtonUp(Microsoft.Xna.Framework.Point point)
        {
            if (_captureControl != null)
                _captureControl.OnLButtonUp(point);
            else
            {
                if (_b3DViewOn == true)
                    m_Board3D.OnLButtonUp(point);
                else
                    m_Board2D.OnLButtonUp(point);

                foreach (var item in childControls)
                {
                    item.OnLButtonUp(point);
                }
            }
        }

        public void OnMouseMoving(Microsoft.Xna.Framework.Point point)
        {
            if (m_Board2D == null || m_Board3D == null)
                return;

            if (_captureControl != null)
                _captureControl.OnMouseMoving(point);
            else
            {
                if (_b3DViewOn == true)
                    m_Board3D.OnMouseMoving(point);
                else
                    m_Board2D.OnMouseMoving(point);

                foreach (var item in childControls)
                {
                    item.OnMouseMoving(point);
                }
            }
        }

        public void OnRButtonDown(Microsoft.Xna.Framework.Point point)
        {
            if (_captureControl != null)
                _captureControl.OnRButtonDown(point);
            else
            {
                if (_b3DViewOn == true)
                    m_Board3D.OnRButtonDown(point);
                else
                    m_Board2D.OnRButtonDown(point);

                foreach (var item in childControls)
                {
                    item.OnRButtonDown(point);
                }
            }
        }

        public void OnRButtonUp(Microsoft.Xna.Framework.Point point)
        {
            if (_captureControl != null)
                _captureControl.OnRButtonUp(point);
            else
            {
                if (_b3DViewOn == true)
                    m_Board3D.OnRButtonUp(point);
                else
                    m_Board2D.OnRButtonUp(point);

                foreach (var item in childControls)
                {
                    item.OnRButtonUp(point);
                }
            }
        }

        public void AnimateMove(Move move)
        {
            if (_b3DViewOn == true)
            {
                m_Board3D.AnimateMove(move);
            }
            else
            {
                m_Board2D.AnimateMove(move);
            }
        }

        void GameMoveEventDoneHandler(object sender, GameMoveDoneEventArgs e)
        {
            if (GameMoveDoneEvent != null)
            {
                GameMoveDoneEvent(this, e);
            }
        }

        void m_SwitchButton_ButtonPressed(object sender, EventArgs e)
        {
            _b3DViewOn = !_b3DViewOn;
        }

        void m_FullScreenButton_ButtonPressed(object sender, EventArgs e)
        {
            graphics.ToggleFullScreen();
        }

        public void SetCapture(IBoardControl control)
        {
            _captureControl = control;
            // SetCapture();
        }

        public void ReleaseCapture()
        {
            _captureControl = null;
            // Window.ReleaseCapture();
        }

        public void AddMove(Move move)
        {
            throw new NotImplementedException();
        }

        public void SetEditMode(bool editMode)
        {
            _inEditMode = editMode;
        }

        public void ClickOnField(Position pos, bool leftButton)
        {
            if (m_GameManager.GameBoard.GetFieldColor(pos.Row, pos.Col) != enumFigureColor.Black)
                return;

            enumFigureType figureType = m_GameManager.GameBoard.GetField(pos);
            enumFigureType newFigureType = enumFigureType.Nothing;

            if (leftButton == true)
            {
                switch (figureType)
                {
                    case enumFigureType.WhiteMan:
                        newFigureType = enumFigureType.WhiteKing; break;
                    case enumFigureType.WhiteKing:
                        newFigureType = enumFigureType.Nothing; break;
                    default:
                        newFigureType = enumFigureType.WhiteMan; break;
                }
            }
            else
            {
                switch (figureType)
                {
                    case enumFigureType.BlackMan:
                        newFigureType = enumFigureType.BlackKing; break;
                    case enumFigureType.BlackKing:
                        newFigureType = enumFigureType.Nothing; break;
                    default:
                        newFigureType = enumFigureType.BlackMan; break;
                }
            }

            m_GameManager.GameBoard.PlaceFigure(pos, newFigureType);
        }
    }
}
